﻿using LServer.Core.Common;
using LServer.Core.Utils;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

namespace LServer.Core.DataTableBase 
{
    /// <summary>
    /// 客户端数据表 的管理类
    /// </summary>
    /// <typeparam name="T">数据表类</typeparam>
    /// <typeparam name="B">数据表管理子类</typeparam>
    public abstract class DataTableDBModelBase<T, B>  
    where T : DataTableEntityBase 
    where B : class , new()
    {
        /// <summary>
        /// data列表
        /// </summary>
        public List<T> Lst { get; private set; }

        /// <summary>
        /// data 字典
        /// </summary>
        public Dictionary<int, T> Dic { get; private set; }

        /// <summary>
        /// 表名字
        /// </summary>
        protected abstract string DataTableFullPath { get; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public DataTableDBModelBase()
        {
            ReadDataTable();
        }

        /// <summary>
        /// 读取表格
        /// </summary>
        private void ReadDataTable()
        {
            byte[] dataByte = LFIOUtil.GetBuffer(DataTableFullPath);

            using (MMO_MemoryStream ms = new MMO_MemoryStream(dataByte))
            {
                //读取 有多少个 数据实体
                int listCount = ms.ReadInt();

                //初始化 list 长度
                Lst = new List<T>(listCount);
                //初始化 dictionary 长度
                Dic = new Dictionary<int, T>(listCount);

                T entity;
                for (int i = 0; i < listCount; i++)
                {
                    entity = GetEntity(ms);

                    Lst.Add(entity);
                    Dic[entity.Id] = entity;
                }
            }
        }

        /// <summary>
        /// 需要 子类去实现
        /// </summary>
        /// <param name="ms"></param>
        /// <returns></returns>
        protected abstract T GetEntity(MMO_MemoryStream ms);

        public T Get(int id) 
        {
            T entity;
            Dic.TryGetValue(id, out entity);
            return entity;
        }
    }
}

